package com.xmbandu.app.activity;

import android.Manifest;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.constraint.ConstraintLayout;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.tbruyelle.rxpermissions2.RxPermissions;
import com.xmbandu.app.R;
import com.xmbandu.app.base.BaseActivity;
import com.xmbandu.app.base.SspConfig;
import com.xmbandu.app.bean.DeviceIdBean;
import com.xmbandu.app.bean.LinkBean;
import com.xmbandu.app.bean.LoginBean;
import com.xmbandu.app.home.MainActivity;
import com.xmbandu.app.httpnet.BaseEntity;
import com.xmbandu.app.httpnet.BaseObserver;
import com.xmbandu.app.httpnet.RetrofitFactory;
import com.xmbandu.app.qrcode.activity.CaptureActivity;
import com.xmbandu.app.receiver.SMSBroadcastReceiver;
import com.xmbandu.app.utils.CommonUtils;
import com.xmbandu.app.utils.RegisterTimeService;
import com.xmbandu.app.utils.RegisterTimer;
import com.xmbandu.app.utils.SspPrefUtils;

import java.util.regex.Pattern;

import io.reactivex.Observable;
import io.reactivex.functions.Consumer;

/**
 * Created by wmq on 2019/4/24.
 */

public class LoginActivity extends BaseActivity {
    private EditText etPhone;
    private EditText etCode;
    private TextView tvCode;
    private ConstraintLayout clSend;
    private ConstraintLayout clLogin;
    private Intent intent;
    private RxPermissions permissions ;
    private TextView agreement;
    private SMSBroadcastReceiver mSMSBroadcastReceiver;
    private static final String ACTION = "android.provider.Telephony.SMS_RECEIVED";
    public static final String USER_URL = "http://wtp.wantupai.com/"+"xieyi.html?from=singlemessage&isappinstalled=0";

    @Override
    public int getLayoutId() {
        return R.layout.activity_login_new;
    }

    @Override
    public void initViews() {
        permissions = new RxPermissions(this);
        RegisterTimeService.setHandler(mCodeHandler);
        etPhone = findViewById(R.id.et_phone);
        etCode = findViewById(R.id.et_code);
        tvCode = findViewById(R.id.tv_code);
        clSend = findViewById(R.id.cl_send);
        clLogin = findViewById(R.id.cl_login);
        agreement = findViewById(R.id.agreement);
    }

    @Override
    public void initListener() {
        setOnClick(clSend);
        setOnClick(clLogin);
        setOnClick(agreement);
    }

    @Override
    public void initData() {
        etCode.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {


            }

            @Override
            public void afterTextChanged(Editable s) {
                if(s.length()==4){
                    phoneLogin(etPhone.getText().toString(), etCode.getText().toString());

                }

            }
        });
    }

    @Override
    public void processClick(View v) {
        switch (v.getId()) {
            case R.id.cl_send:
                if (TextUtils.isEmpty(etPhone.getText().toString())) {
                    Toast.makeText(this, "请输入手机号", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (etPhone.getText().length() != 11) {
                    Toast.makeText(this, "手机号格式不对", Toast.LENGTH_SHORT).show();
                    return;
                }
                if(CommonUtils.isClickable()){
                    sendSms(etPhone.getText().toString());
                }
                break;
            case R.id.cl_login:
                if (TextUtils.isEmpty(etCode.getText().toString())) {
                    Toast.makeText(this, "请输入验证码", Toast.LENGTH_SHORT).show();
                    return;
                }
                phoneLogin(etPhone.getText().toString(), etCode.getText().toString());
                break;

            case R.id.agreement:
                SspCommonWebActivity.intoSspCommonWeb(getBaseContext(), USER_URL, "#ffffff", true);
                break;
        }

    }

    @Override
    protected void onStart() {
        super.onStart();
        //生成广播处理
        mSMSBroadcastReceiver = new SMSBroadcastReceiver();

        //实例化过滤器并设置要过滤的广播
        IntentFilter intentFilter = new IntentFilter(ACTION);
        intentFilter.setPriority(Integer.MAX_VALUE);
        //注册广播
        this.registerReceiver(mSMSBroadcastReceiver, intentFilter);

        mSMSBroadcastReceiver.setOnReceivedMessageListener(new SMSBroadcastReceiver.MessageListener() {
            @Override
            public void onReceived(String message) {

                etCode.setText(message);

            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
//        closeTimer();
//        if(intent!=null)
//            stopService(intent);
        //注销短信监听广播
//        mCodeHandler.removeCallbacksAndMessages(null);
//        RegisterTimeService.setHandler(null);
//        RegisterTimer.setHandler(null);
        this.unregisterReceiver(mSMSBroadcastReceiver);
    }

    /**
     * 登录接口
     * @param phonenum
     * @param code
     */
    private void phoneLogin(String phonenum, String code) {
        Observable observable = RetrofitFactory.getInstance().login(phonenum, code);
        observable.compose(compose(this.bindToLifecycle())).subscribe(new BaseObserver<LoginBean>(this) {

            @Override
            protected void onHandleSuccess(LoginBean loginBean) {
                Log.e("login", "onHandleSuccess: " + loginBean.getDeviceid());
                SspPrefUtils.setString("token", loginBean.getToken());
                SspPrefUtils.setString("deviceid", loginBean.getDeviceid());
                Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                startActivity(intent);
                finish();

//                gotoPermissions();

            }

            @Override
            public void onNext(BaseEntity<LoginBean> value) {
                Log.e("login", "onNext: " + value.getMsg());
                super.onNext(value);
            }
        });
    }



    /**
     * 申请权限
     */
    private void gotoPermissions() {
        permissions.request(Manifest.permission.CAMERA).subscribe(new Consumer<Boolean>() {
            @Override
            public void accept(Boolean aBoolean) throws Exception {
                if (aBoolean){
                    //申请的权限全部允许
                    // 二维码扫码
                    if(TextUtils.isEmpty(SspPrefUtils.getString("deviceid",""))){
                        Intent intent = new Intent(LoginActivity.this, CaptureActivity.class);
                        startActivityForResult(intent,SspConfig.REQ_QR_CODE);

                    }else {
                        Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                        startActivity(intent);
                        finish();
                    }
                }else{
                    //只要有一个权限被拒绝，就会执行
                    Toast.makeText(LoginActivity.this, "未授权权限，部分功能不能使用", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    Handler mCodeHandler = new Handler() {
        public void handleMessage(Message msg) {
            if (msg.what == RegisterTimer.IN_RUNNING) {// 正在倒计时
                clSend.setClickable(false);
                clSend.setEnabled(false);
                clSend.setFocusable(false);
                String a = msg.obj.toString();
                tvCode.setText(a);
            } else if (msg.what == RegisterTimer.END_RUNNING) {// 完成倒计时
                tvCode.setText("重新获取");
                clSend.setFocusable(true);
                clSend.setEnabled(true);
                clSend.setClickable(true);
            }
        }
    };
    /**
     * 开启倒计时
     */
    public void startTimer() {
        if (intent == null) {
            intent = new Intent(getBaseContext(), RegisterTimeService.class);
            startService(intent);
        }else {
            startService(intent);

        }

    }
    /**
     * 关闭倒计时
     */
    public void closeTimer(){
        if(intent==null){
            intent = new Intent(getBaseContext(), RegisterTimeService.class);
            stopService(intent);

        }else{
            stopService(intent);
        }
    }

    /**
     * 发送验证码
     *
     * @param phonenum
     */
    private void sendSms(String phonenum) {
        if (!Pattern.compile("^((13[0-9])|(14[5,7,9])|(15[0-3,5-9])|(166)|(17[3,5,6,7,8])" +
                "|(18[0-9])|(19[8,9]))\\d{8}$").matcher(phonenum).matches()) {
            Toast.makeText(this, "请输入正确的手机号码", Toast.LENGTH_SHORT).show();
            return;
        }
        startTimer();
        Observable observable = RetrofitFactory.getInstance().sendSMS(phonenum);
        observable.compose(compose(this.bindToLifecycle())).subscribe(new BaseObserver(this) {
            @Override
            protected void onHandleSuccess(Object o) {


            }

            @Override
            public void onNext(Object o) {
                Log.e("验证码", "onHandleSuccess: " + o.toString());
//                getcode.setVisibility(View.GONE);
//                codeTime.setVisibility(View.VISIBLE);
            }

            @Override
            public void onError(Throwable e) {
                super.onError(e);
                Log.e("验证码", "onError " + e.toString());
            }
        });
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //扫描结果回调
        if (requestCode == SspConfig.REQ_QR_CODE && resultCode == RESULT_OK) {
            Bundle bundle = data.getExtras();
            String scanResult = bundle.getString(SspConfig.INTENT_EXTRA_KEY_QR_SCAN);
            //将扫描出的信息显示出来
//            tvResult.setText(scanResult);
            getDeviceId(scanResult);
        }
    }

    /**
     * 获取device
     */
    private void getDeviceId(String scanResult) {
        Observable observable = RetrofitFactory.getInstance().getDeviece(scanResult);
        observable.compose(compose(this.bindToLifecycle())).subscribe(new BaseObserver<DeviceIdBean>(this) {

            @Override
            protected void onHandleSuccess(DeviceIdBean deviceIdBean) {
                Log.e("deviceid", "onHandleSuccess: " + deviceIdBean.getDeviceid());
                Toast.makeText(LoginActivity.this,"激活成功",Toast.LENGTH_SHORT).show();
                SspPrefUtils.setString("deviceid", deviceIdBean.getDeviceid());
                Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                startActivity(intent);
                finish();
            }

            @Override
            protected void onHandleError(String msg) {
                super.onHandleError(msg);
            }
        });
    }

}
